using System;
using System.Collections.Generic;
using System.Linq;
using Granite.Collections;
using System.Collections.ObjectModel;

namespace Toon.Models.Catalogs
{
    public class Table<T> : Collection<TableItem<T>>, IChoosable<T>
    {
        readonly string m_Name;
		readonly List<T> m_SelectionList = new List<T>();

        public Table(string name, IEnumerable<TableItem<T>> items)
            : base(items.ToList())
        {
            m_Name = name;
			Initialize();
        }

        public Table(string name, params TableItem<T>[] items)
            : base(items)
        {
            m_Name = name;
			Initialize();
		}

        public Table(string name, IEnumerable<T> items)
            : base(items.Select(i => new TableItem<T>(i)).ToList())
        {
            m_Name = name;
			Initialize();
		}

        public Table(string name, params T[] items)
            : base(items.Select(i => new TableItem<T>(i)).ToList())
        {
            m_Name = name;
			Initialize();
		}


		private void Initialize()
		{
			foreach (var item in this)
				for (int i = 0; i < item.Frequency; i++)
					m_SelectionList.Add(item.Item);
		}

        public string Name
        {
            get { return m_Name; }
        }

		public T ChooseOne(Random rand = null)
		{
			if (rand == null)
				rand = new Random();

			return rand.ChooseOne(m_SelectionList);
		}
    }
}
